# pages/ota_page.py
from pages.base_page import BasePage
import time

class OTAPage(BasePage):
    MAX_RETRIES = 3
    UPGRADE_TIMEOUT = 720  # 12分钟
    
    def perform_ota_cycle(self, max_cycles=100):
        """执行完整的OTA升级周期"""
        for cycle in range(1, max_cycles+1):
            self.logger.info(f"开始第 {cycle} 次升级循环")
            if self._try_upgrade_flow():
                self._post_upgrade_actions()
            else:
                self.logger.warning("未检测到可用升级")
            time.sleep(300)  # 5分钟间隔
            
    def _try_upgrade_flow(self):
        """带重试的升级流程"""
        for attempt in range(1, self.MAX_RETRIES+1):
            try:
                if self._check_upgrade_available():
                    self._execute_upgrade()
                    return True
                self._navigate_to_ota_menu()
            except Exception as e:
                self.logger.error(f"升级尝试 {attempt} 失败: {str(e)}")
                self.take_screenshot(f"upgrade_retry_{attempt}")
        return False
        
    def _check_upgrade_available(self):
        try:
            return self.find_element('upgrade_confirm_button', timeout=5)
        except:
            return False
            
    def _execute_upgrade(self):
        self.click_element('upgrade_confirm_button')
        self.click_element('start_upgrade_button')
        self._monitor_upgrade_progress()
        self._handle_upgrade_complete()
        
    def _monitor_upgrade_progress(self):
        start_time = time.time()
        while time.time() - start_time < self.UPGRADE_TIMEOUT:
            try:
                if self.find_element('upgrade_complete_text', timeout=5):
                    break
            except:
                pass
            time.sleep(10)
            self.logger.info("升级进行中...")
            
    def _handle_upgrade_complete(self):
        self.click_element('complete_confirm_button')
        self.navigate_back()
        
    def _navigate_to_ota_menu(self):
        self.click_element('device_menu_button')
        self.click_element('ota_menu_item')
        time.sleep(2)
        
    def _post_upgrade_actions(self):
        self.click_element('enter_device_button')
        self.click_element('location_permission_close')
        time.sleep(20)
        
    def navigate_back(self):
        self.driver.back()